//
//  RHAddDeviceController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/7/27.
//

#import "RHAddDeviceController.h"
#import "RHAddDeviceCell.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "RHNetDevInfoModel.h"
#import "NSString+YYUtil.h"
#import "RHBaseWebViewController.h"
#import "RHSelectInstallerVC.h"

@interface RHAddDeviceController ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *headerView;

@property (nonatomic ,strong) UIView *footerView;

@property (nonatomic ,strong)QMUIButton *deleteBtnB;

@property (nonatomic ,strong)UIImageView *deviceImg;

@property (nonatomic ,copy)NSString *uploadImgUrl;

@property (nonatomic,strong)NSMutableDictionary *para;

//1:扫描设备id  2:扫描密钥
@property (nonatomic ,assign) NSInteger scanIndex;

@property (nonatomic ,strong) NSArray *titleArr;

@property (nonatomic ,strong) NSArray *placeHoldArr;

@property (nonatomic ,strong) QMUITextField *deviceIdTextfield;
@end

@implementation RHAddDeviceController
-(NSMutableDictionary *)para
{
    if(!_para){
        _para = [NSMutableDictionary dictionary];
    }
    return _para;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"添加设备".rh_localized;
    
    [self setupUI];
}


- (void)setupUI{
    
    self.titleArr = @[@"设备ID".rh_localized];
    self.placeHoldArr = @[@"请输入设备ID".rh_localized];
    //除普通用户外要填密钥,其他的角色都不用填
//    if ([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser) {
//        self.titleArr = @[@"设备名称".rh_localized,@"设备ID".rh_localized,@"设备密钥".rh_localized,@"设备类型".rh_localized];
//        self.placeHoldArr = @[@"请输入设备名称".rh_localized,@"请输入设备ID".rh_localized,@"请输入设备密钥".rh_localized,@"请输入设备类型".rh_localized];
//    }
    QMUIButton *helpBtn = [[QMUIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    [helpBtn setImage:[UIImage imageNamed:@"network_help"] forState:UIControlStateNormal];
    [helpBtn addTarget:self action:@selector(addDeviceHelp) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc]initWithCustomView:helpBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 15)];
    _tableView.tableFooterView = self.footerView;
    [_tableView registerClass:[RHAddDeviceCell class] forCellReuseIdentifier:@"RHAddDeviceCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [self.tableView reloadData];
    
    QMUIButton *createBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [createBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [createBtn setTitle:@"确认".rh_localized forState:UIControlStateNormal];
    [createBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [createBtn.layer setCornerRadius:8];
    [createBtn setBackgroundColor:CMainColorGreen];
    [self.view addSubview:createBtn];
    [createBtn addTarget:self action:@selector(getDeviceInfo) forControlEvents:UIControlEventTouchUpInside];
    [createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.mas_equalTo(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(self.deviceId.length > 0){
            RHAddDeviceCell *deviceIdCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
            deviceIdCell.textField.text = self.deviceId;
        }
        if(self.deviceType.length > 0){
            RHAddDeviceCell *deviceTypeCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
            deviceTypeCell.textField.text = self.deviceType;
        }
    });
}

-(void)addDeviceHelp
{
    RHBaseWebViewController *helpVC = [[RHBaseWebViewController alloc]init];
    helpVC.urlStr = @"http://us.energycloudx.com/tutorial.pdf";
    [self.navigationController pushViewController:helpVC animated:YES];
}

- (UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,300)];
        [_footerView setBackgroundColor:UIColor.clearColor];
        _footerView.clipsToBounds = YES;
        
        
        UIView *view =  [[UIView alloc] initWithFrame:CGRectMake(15, 15, SCREEN_WIDTH-30,200)];
        [view setBackgroundColor:UIColor.whiteColor];
        [view rounded:8 width:1 color:kBorderColor];
        [_footerView addSubview:view];
        
        
        QMUILabel *lab = [[QMUILabel alloc] init];
        [lab setText:@"上传设备安装图片".rh_localized];
        [lab setTextAlignment:NSTextAlignmentLeft];
        [lab setFont:[UIFont systemFontOfSize:14]];
        [lab setTextColor:kCOLOR_HEX(@"3F4443")];
        [_footerView addSubview:lab];
        
        
        QMUIButton *addPicBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [addPicBtn.layer setCornerRadius:8];
        [addPicBtn setBackgroundColor:kCOLOR_HEX(@"F3F7FF")];
        //[btn setBackgroundImage:[UIImage imageNamed:@"mask_group"] forState:UIControlStateNormal];
        [addPicBtn setImagePosition:QMUIButtonImagePositionTop];
        [addPicBtn setImage:[UIImage imageNamed:@"kwt_plant_camera"] forState:UIControlStateNormal];
        [addPicBtn setTitle:@"添加图片".rh_localized forState:UIControlStateNormal];
        [addPicBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
        [addPicBtn setSpacingBetweenImageAndTitle:5];
        [addPicBtn setTitleColor:kCOLOR_HEX(@"AAAAAA") forState:UIControlStateNormal];
        [_footerView addSubview:addPicBtn];

        
        

        kWeakSelf;
        _deviceImg = kImageView;
        _deviceImg.contentMode = UIViewContentModeScaleAspectFill;
        _deviceImg.layer.cornerRadius = 8;
        _deviceImg.layer.masksToBounds = YES;
        [_footerView addSubview:_deviceImg];
        _deviceImg.hidden = YES;
        
        [_deviceImg mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.equalTo(addPicBtn);
        }];
        
        QMUIButton *deleteBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [deleteBtn setImage:[UIImage imageNamed:@"pic_delete_icon"] forState:UIControlStateNormal];
        [deleteBtn setBackgroundColor:UIColor.clearColor];
        [_footerView addSubview:deleteBtn];
        self.deleteBtnB = deleteBtn;
        self.deleteBtnB.hidden = YES;
        
        [[deleteBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.deviceImg.image = nil;
            weakSelf.deviceImg.hidden = YES;
            weakSelf.deleteBtnB.hidden = YES;
            weakSelf.uploadImgUrl = nil;
        }];
        
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(30, 30));
            make.right.equalTo(addPicBtn).offset(10);
            make.top.equalTo(addPicBtn).offset(-10);
        }];
        
        
        [[addPicBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf addPicAction];
        }];
        
        
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(30);
            make.top.mas_offset(40);
            make.right.mas_offset(-30);
            make.height.mas_equalTo(20);
        }];
        
        [addPicBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(90, 90));
            make.left.equalTo(lab);
            make.top.equalTo(lab.mas_bottom).offset(10);
        }];
        
        
    }
    return _footerView;
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.titleArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RHAddDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHAddDeviceCell"];

    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSString *titleStr = [self.titleArr safeObjectAtIndex:indexPath.row];
    [cell.titleLab setText:titleStr];
    [cell.textField setPlaceholder:[self.placeHoldArr safeObjectAtIndex:indexPath.row]];
    cell.textField.delegate = self;
    [cell.bgView rounded:8 width:1 color:kBorderColor];
    if([titleStr isEqualToString:@"设备ID".rh_localized] || [titleStr isEqualToString:@"设备密钥".rh_localized]){
        cell.textField.maximumTextLength = 32;
        
        QMUIButton *scanBtn = [[QMUIButton alloc]init];
        [scanBtn setImage:[UIImage imageNamed:@"input_scan_icon"] forState:UIControlStateNormal];
        [cell.bgView addSubview:scanBtn];
//        [scanBtn addTarget:self action:@selector(scanQRC) forControlEvents:UIControlEventTouchUpInside];
        [scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.height.offset(35);
                    make.centerY.mas_offset(0);
                    make.right.mas_offset(-15);
        }];
        [cell.textField mas_updateConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-40);
        }];
        
        kWeakSelf;
        [[scanBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            if ( [titleStr isEqualToString:@"设备ID".rh_localized]) {
                weakSelf.scanIndex = 1;
            }
            if ( [titleStr isEqualToString:@"设备密钥".rh_localized]) {
                weakSelf.scanIndex = 2;
            }
            [weakSelf scanQRC];
        }];
    }
    if([titleStr isEqualToString:@"设备ID".rh_localized]){
        self.deviceIdTextfield = cell.textField;
    }
    if([titleStr isEqualToString:@"设备类型".rh_localized]){
        cell.textField.userInteractionEnabled = NO;
    }
    [cell hideArrowView:YES];
    [cell hideLine:indexPath.row == self.titleArr.count-1];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark -----1. 根据设备id获取设备类型

-(void)getDeviceInfo
{
    //设备ID
    RHAddDeviceCell *deviceIdcell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    NSString *deviceId = deviceIdcell.textField.text;
    NSString *regex = @"^[A-Za-z0-9]+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if(![pred evaluateWithObject:deviceId]){
        [QMUITips showError:@"设备ID请输入数字和字母".rh_localized];
        return;
    }
    
    //除普通用户外要填密钥,其他的角色都不用填
//    if ([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser) {
//        RHAddDeviceCell *passwordCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
//        if(passwordCell.textField.text.length==0){
//            [QMUITips showError:@"请输入设备密钥".rh_localized];
//            return;
//        }
//    }
    
    //后面设备上传的时候加多了个D
   
    deviceId = [@"D" stringByAppendingString:deviceId];
  
    NSDictionary *para = @{@"deviceId":deviceId
                           };//@"password":passwordCell.textField.text 去掉
    
    //查询是否有绑定设备,如果没有就先绑定设备后再配网
   
    [QMUITips showLoading:@"获取设备信息...".rh_localized inView:self.view];
    [RHNetDevInfoModel startGetWithCompletionAPIKey:H_deviceBindStatus_V3 argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        if(resultModel.code == 200){
            [self.para removeAllObjects];
            
            RHNetDevInfoModel *model = resultModel.data;
//            if (model.direct == 1) {
                //直接走添加流程
                [self checkInfoWithDeviceType:SafeStr(model.deviceTypeCode) deviceId:deviceId];
//            }
//            if (model.direct == 0){
//                //设备在安装商那里,需要选择一个安装工人进行绑定
//                [self selectInstallerWithDeviceType:SafeStr(model.deviceTypeCode) deviceId:deviceId userId:model.userId];
//            }
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark ----- 选择安装工人
-(void)selectInstallerWithDeviceType:(NSString *)deviceType deviceId:(NSString *)deviceId userId:(NSInteger)userId
{
    kWeakSelf;
    RHSelectInstallerVC *vc = [[RHSelectInstallerVC alloc]init];
    vc.userId = userId;
    vc.selectBlock = ^(NSInteger installerUserId) {
        [weakSelf.para setObject:@(installerUserId) forKey:@"userId"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf checkInfoWithDeviceType:deviceType deviceId:deviceId];
        });
        
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ----- 2. 有图片先压缩图片-->上传图片,提交参数  没有图片就直接提交参数 -----
-(void)checkInfoWithDeviceType:(NSString *)deviceType deviceId:(NSString *)deviceId
{
  
    [self.para removeAllObjects];
    
    //除普通用户外要填密钥,其他的角色都不用填
    [self.para setObject:SafeStr(deviceId) forKey:@"deviceId"];
    [self.para setObject:SafeStr(deviceId) forKey:@"deviceName"];
    [self.para setObject:SafeStr(deviceType) forKey:@"deviceType"];
    
    //图片非必传
    if(self.deviceImg.image == nil){
//        [QMUITips showError:@"请上传图片".rh_localized];
//        return;
        [self bindDevice];
    }else{
        kWeakSelf;
        //压缩到500K
        [QMUITips showLoading:@"压缩图片...".rh_localized inView:kAppWindow];
        UIImage *image = self.deviceImg.image;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *compressImg = [self compressImageQuality:image toByte:2000];
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllTipsInView:kAppWindow];
                //清除上次上传的
                weakSelf.uploadImgUrl = nil;
                //上传图片
                [weakSelf uploadHeadImage:compressImg];
            });
        });
    }
    
    

}

#pragma mark --------3. 提交参数 ------
-(void)bindDevice{
    [QMUITips showLoading:@"绑定设备...".rh_localized inView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_deviceUserBind argument:self.para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"绑定设备成功".rh_localized inView:self.view hideAfterDelay:1];
            //此时用户变为终端用户,重新获取用户信息,重载tabbar
            if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser){
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                        [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                    }];
                });
            }else{
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if(self.AddSucceseBlock){
                        self.AddSucceseBlock();
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                });
            }
            
            
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

//-(void)textFieldDidEndEditing:(UITextField *)textField{
//    if (![textField isEqual:self.deviceIdTextfield]) {
//        return;
//    }
//    RHAddDeviceCell *deviceNameCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//    if([textField isEqual:deviceNameCell.textField])return;
//    
//    
//    RHAddDeviceCell *deviceIdcell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
//    NSString *content = deviceIdcell.textField.text;
//    NSString *regex = @"[A-Za-z0-9]*";
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//    if(![pred evaluateWithObject:content]&&[textField isEqual:deviceIdcell]){
//        [QMUITips showError:@"设备ID请输入数字和字母".rh_localized];
//        return;
//    }
//    
//    //除普通用户外要填密钥,其他的角色都不用填
//    if ([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser) {
//        RHAddDeviceCell *passwordCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
//        if(passwordCell.textField.text.length==0&&[textField isEqual:passwordCell]){
//            [QMUITips showError:@"请输入设备密钥".rh_localized];
//            return;
//        }
//    }
//   
//
//    [self getDeviceInfo];
//}


#pragma mark - Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"拍照".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = YES;
    camera.allowRecordVideo = NO;
    
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        weakSelf.deviceImg.image = image;
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.deviceImg.hidden = NO;
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑
    actionSheet.configuration.allowEditImage = NO;
    
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
    
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        UIImage *image = images[0];
        weakSelf.deviceImg.image = image;
        weakSelf.deleteBtnB.hidden = NO;
        weakSelf.deviceImg.hidden = NO;
        //        NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
        //        NSLog(@"--->图片大小: %ld k", (long)(imageData.length / 1024));
       
    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}

#pragma mark --------2.1 图片上传 ----------------
//压缩图片质量   maxLength  单位: kb
- (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    
     CGFloat compression = 1;
     NSData *data = UIImageJPEGRepresentation(image, compression);
     while (data.length / 1024 > maxLength && compression > 0) {
         compression -= 0.05;
         // When compression less than a value, this code dose not work
         data = UIImageJPEGRepresentation(image, compression);
         NSLog(@"====>压缩了一次后: %ld k",(long)(data.length / 1024));
     }
     UIImage *resultImage = [UIImage imageWithData:data];
     return resultImage;
}

#pragma mark --------2.2 图片上传 ----------------
-(void)uploadHeadImage:(UIImage*)headImg
{
    kWeakSelf;
    [QMUITips showLoading:@"上传图片...".rh_localized inView:self.view];
    [BaseModel startUploadWithCompletionAPIKey:H_uploadImage rgument:@{@"file":@"ios"} image:headImg imageName:nil requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"上传成功".rh_localized inView:weakSelf.view];
            //保存图片参数
            weakSelf.uploadImgUrl = request.responseObject[@"url"];
            
            [weakSelf.para setObject:weakSelf.uploadImgUrl forKey:@"deviceImage"];
            
            [weakSelf bindDevice];
        }
        
        
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
            
            
        }];
    
}


#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    //扫描设备id  后面设备那边上传的时候 加多了个D
                    if (weakSelf.scanIndex == 1) {
                        RHAddDeviceCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
                        cell.textField.text = content;
                        //获取设备信息
//                        [self getDeviceInfo];
                    }
                    //扫描密钥
                    if (weakSelf.scanIndex == 2) {
                        RHAddDeviceCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
                        NSString *secret = [NSString base64Decode:content];
                        if (secret.length == 0) {
                            [QMUITips showInfo:@"二维码无效".rh_localized];
                        }
                        cell.textField.text = secret;
                    }
                    
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}
@end
